<?php
class LinesAction extends ZMAction {
    public function index(){
        $devid = $_REQUEST['devid'];
        $model = M('LinesDev');
        
        $porttype = $this->getPortType($devid);//取得源的设备的端口类型作为连接线的类型
        
        if($porttype===false){
            $metadata['editable'] = false;
            $this->ajaxReturnWithMeta(null,'不支持的类型!',true,$metadata);
            return;
        }
        
        $map['devid'] = $devid;
        $subQuery = $model->field('lineid')->where($map)->select(false);
        $where['devid'] = array('neq',$devid); //排除自己
        $where['_string'] = " lineid in $subQuery";
        $result = $model->where($where)->select();
        if($result){
            foreach($result as &$row){
                $row['devname'] = $this->getDevName($row['devid']);
            }
        }else{
            $result = array();
        }
        $metadata['editable'] = true;
        $metadata['devname'] = $this->getDevName($devid);
        $this->ajaxReturnWithMeta($result,count($result),true,$metadata);
    }
    
    public function save(){
        $cid = $_REQUEST['cid'];
        $sdevid = $_REQUEST['sdevid'];//源
        $lineid = $_REQUEST['lineid'];
        $devid = $_REQUEST['devid'];
        
        $modelLines = M('Lines');
        $modelLinesDev = M('LinesDev');

        $porttype = $this->getPortType($sdevid);//取得源的设备的端口类型作为连接线的类型
        
        if($porttype===false){
            $this->error('端口类型不明！');
        }else{
            if(empty($cid)){//新添加连接
                $ret = $this->connect($sdevid,$devid);
                if($ret){
                    $this->success('连接成功!');
                }else{
                    $this->error('操作失败，数据库错误！');
                }
            }else{ //属于修改连接
                $map['cid'] = $cid;
                $resLinesDev = $modelLinesDev->where($map)->find();
                if($resLinesDev){ //找到原来的信息
                    $lineid = $resLinesDev['lineid']; //找到原来的连接线
                    $oldDevid = $resLinesDev['devid']; //找到原来连接的设备
                    $this->disconnect($sdevid,$oldDevid);
                    $this->connect($sdevid,$devid);
                    $this->success('修改成功！');
                }else{
                    $this->error('连接已经被删除，请刷新后再修改！');
                }
            }            
        }
    }
    
    public function del(){
        $cid = $_REQUEST['cid'];
        $modelLines = M('Lines');
        $modelLinesDev = M('LinesDev');
        $map['cid'] = $cid;
        $resLinesDev = $modelLinesDev->where($map)->find();
        if($resLinesDev){ //找到原来的信息
            $lineid = $resLinesDev['lineid']; //找到原来的连接线
            $modelLinesDev->where($map)->delete();
            $count = $modelLinesDev->where("lineid=$lineid")->count();
            if($count<2){ //仅连接了一个设备
                //需要删除连接线
                unset($map);
                $map['lineid'] = $lineid;
                $modelLinesDev->where($map)->delete();
                $modelLines->where($map)->delete();
            }
            
//            $oldDevid = $resLinesDev['devid']; //找到原来连接的设备
//            $this->disconnect($sdevid,$oldDevid);
        }
        $this->success('删除成功！');
    }
    
    public function delLine(){
        $lineid = $_REQUEST['lineid'];
        $modelLines = M('Lines');
        $modelLinesDev = M('LinesDev');
        $map['lineid'] = $lineid;
        $modelLinesDev->where($map)->delete();
        $modelLines->where($map)->delete();
        $this->success('删除成功！');
    }
    
    
    /**
    * 获取可连接端口设备树
    * 
    */
    public function PortTree(){
        $devid = $_REQUEST['devid'];
        if(empty($devid)){
            $porttype=-1;
        }else{
            //先取出端口类别
            $porttype = $this->getPortType($devid);
            if($porttype === false){
                echo '[]';
                return;
            }
        }
        
        
        
        $res = $this->getPortTree(0,$porttype);
        echo(json_encode($res));
        
//        //先列举端口信息的节点
//        $modelDev = M('Dev');
//        $map['ddid'] = C('PORTINFO');
//        $map['istemp'] = 0;
//        $resPort = $modelDev->where($map)->select();
//        foreach($resPort as $row){
//            $ret = $this->getAttrByName($row['devid'],C('PORTTYPENAME'));
//            if($ret){
//                if($ret['value'] == $porttype){ //仅端口类型相同的
//                    
//                }
//            }    
//        }
    }
    
    protected function getPortTree($devid,$ptype){
        $modelDev = M('Dev');
        $porttype = $this->getPortType($devid);
        if($porttype === false){//该设备不是端口
            $retArr = array();
            $map['parentid'] = $devid;
            $map['istemp'] = 0;
            $res = $modelDev->where($map)->select();
            foreach($res as $row){
                $port = $this->getPortTree($row['devid'],$ptype);
                if($port !== false){
                    $retArr[] = $port;
                }
            }
            if(count($retArr)>0){
                $ret['id'] = $devid;
                $ret['text'] = $this->getDevName($devid);
                $ret['expanded'] = true;
                $ret['children'] = $retArr;
                return $ret;
            }
        }else{ //是端口
            if(($porttype == $ptype) || ($ptype==-1)){
                //$retArr = array();
                $res = $modelDev->where("devid=$devid")->find();
                if($res){
                    $ret['id'] = $devid;
                    $ret['text'] = $res['devname'];
                    $ret['leaf'] = true;
                }
                //$retArr[] = $ret;
                return $ret;
            }
        }
        return false;
    }
    
    /**
    * 建立连接
    * 
    * @param mixed $sdevid
    * @param mixed $edevid
    */
    protected function connect($sdevid,$edevid){
        $modelLines = M('Lines');
        $modelLinesDev = M('LinesDev');
        
        $sporttype = $this->getPortType($sdevid);
        if($sporttype===false){
            return false;
        }
        
        $eporttype = $this->getPortType($edevid);
        if($eporttype===false){
            return false;
        }

        $map['devid'] = $sdevid;
        $subQuery = $modelLinesDev->field('lineid')->where($map)->select(false); //查找到跟源设备相连的所有连接线
        $where['devid'] = $edevid; //查找目标是否已经连着
        $where['_string'] = " lineid in $subQuery";
        $resLines = $modelLinesDev->where($where)->find();
        if($resLines){ //如果已经存在了的话
            return true;
        }else{ //没有的话，添加
        
            $porttype = $this->getPortType($sdevid);//取得源的设备的端口类型作为连接线的类型
        
            $sDevName = $this->getDevName($sdevid);
            $eDevName = $this->getDevName($edevid);
            $lineData['linename'] = "[$sDevName]<->[$eDevName]";
            $lineData['linetype'] = $porttype;
            $lineid = $modelLines->add($lineData);
            if($lineid!==false){//添加成功
                $data['lineid'] = $lineid;
                $data['devid'] = $sdevid;
                $modelLinesDev->add($data);
                
                unset($data);
                $data['lineid'] = $lineid;
                $data['devid'] = $edevid;
                $modelLinesDev->add($data);
                
                return true;
            }else{
                return false;
            }
        }        
    }
    
    /**
    * 拆除连接
    * 
    * @param mixed $sdevid
    * @param mixed $edevid
    */
    protected function disconnect($sdevid,$edevid){
        $modelLines = M('Lines');
        $modelLinesDev = M('LinesDev');
        
        $map['devid'] = $sdevid;
        $subQuery = $modelLinesDev->field('lineid')->where($map)->select(false); //查找到跟源设备相连的所有连接线
        $where['devid'] = $edevid; //查找连接线目标是edevid的连接线
        $where['_string'] = " lineid in $subQuery";
        $res = $modelLinesDev->where($where)->select(); //查找出所有相连的记录
        $dellines = array();
        foreach($res as $row){
            $lineid = $row['lineid'];
            $count = $modelLinesDev->where("lineid=$lineid")->count();
            if($count<=2){ //仅连接了两个设备
                $dellines[] = $lineid; //需要删除连接线
            }
        }
        $modelLinesDev->where($where)->delete();
        foreach($dellines as $lineid){
            $modelLines->where("lineid=$lineid")->delete();
            $modelLines->where("lineid=$lineid")->delete();
        }
        return true;
    }
    
    protected function getPortType($devid){
        $model = M('Dev');
        $map['parentid'] = $devid;
        $map['ddid'] = C('PORTINFO');
        $map['istemp'] = 0;
        $resDev = $model->where($map)->find();
        if($resDev){
            $ret = $this->getAttrByName($resDev['devid'],C('PORTTYPENAME'));
            if($ret){
                return $ret['value'];
            }
        }
        return false;
    }
    
    protected function getDevName($devid,$s=''){
        $model = M('Dev');
        $res = $model->where("devid=$devid")->find();
        if($res){
            if(empty($s)){
                $s = $res['devname'];
            }else{
                $s = $res['devname'] . '->' . $s;
            }
            if($res['isattr'] == 1){
                return $this->getDevName($res['parentid'],$s);
            }else{
                return $s;
            }
        }else{
            return $s;
        }
    }
    
    protected function getPortBH($devid){
        $ret = $this->getDevAttrVal($devid,C('PORTNUM'));
        if($ret){
            return $ret['value'];
        }else{
            return '';
        }
    }
    
    public function search(){
        $keyword = $_REQUEST['keyword'];
        $start = $_REQUEST['start'];
        $limit = $_REQUEST["limit"];
        $sort = $_REQUEST['sort'];
        $dir = $_REQUEST['dir'];
        if(!is_numeric($start)){
            $start = 0;
        }
        if(!is_numeric($limit)){
            $limit = 20;
        }
        
        $modelLines = M('Lines');
        $modelLinesDev = M('LinesDev');
        if(!empty($keyword)){
            $model = M('ValStr');
            $modelAttr = M('DevAttr');
            $modelDev = M('Dev');
            $map['val'] = array('like',"%$keyword%");
            $subQuery = $model->field('id')->where($map)->select(false);
            $where['attrid'] = C('PORTNUM');
            $where['_string'] = "val in $subQuery";
            $subSql = $modelAttr->Distinct(true)->field('devid')->where($where)->select(false);
            unset($where);
            $where['_string'] = "devid in $subSql";
            $sql1 = $modelDev->field('parentid')->where($where)->select(false);
            unset($where);
            $where['_string'] = "devid in $sql1";
            $sql = $modelLinesDev->field('lineid')->where($where)->select(false);
            
            unset($where);
            $where['linename'] = array('like',"%$keyword%");
            $where['_string'] = "lineid in $sql";
            $where['_logic'] = 'or';
            
            $count = $modelLines->where($where)->count();
            $result = $modelLines->where($where)->limit("$start,$limit")->select();
        }else{
            $count = $modelLines->count();
            $result = $modelLines->limit("$start,$limit")->select();
        }
        if($result){
            
        }else{
            $result = array();
        }
        
        $modelEnum = M('ValTypeComboEnum');
        foreach($result as &$row){
            $linetype = $row['linetype'];
            unset($where);
            $where['vtid'] = 9;
            $where['id'] = $linetype;
            $res = $modelEnum->where($where)->find();
            if($res){
                $row['typename'] = $res['val'];
            }
            
            unset($where);
            $where['lineid'] = $row['lineid'];
            $row['devnum'] = $modelLinesDev->where($where)->count();
            $res = $modelLinesDev->where($where)->select();
            $i=0;
            foreach($res as $dev){
                if($i==0){
                    $row['dev1id'] = $dev['devid'];
                    $row['dev1name'] = $this->getDevName($dev['devid']);
                    $row['dev1bh'] = $this->getPortBH($dev['devid']);
                }else if($i==1){
                    $row['dev2id'] = $dev['devid'];
                    $row['dev2name'] = $this->getDevName($dev['devid']);
                    $row['dev2bh'] = $this->getPortBH($dev['devid']);
                }else{
                    $row['desc'] .= $this->getDevName($dev['devid']) . ' ';
                    $row['desc'] .= $this->getPortBH($dev['devid']) . ' ';
                }
                $i++;
            }
        }
        $this->ajaxRetArray($result,$count);
    }
    
    public function getLines(){
        $model = M('Lines');
        $modLineXYZ = M('LinesXyz');
        $modLineDev = M('LinesDev');
        $lineid = $_REQUEST['lineid'];
        if(empty($lineid)){
            $resLines = $model->select();
        }else{
            $resLines = $model->where("lineid=$lineid")->select();
        }
        foreach($resLines as &$row){
            $map['lineid'] = $row['lineid'];
            $resXyz = $modLineXYZ->where($map)->order('ordernum,lid')->select();
            if($resXyz){
                $row['xyz'] = $resXyz;
            }else{
                $row['xyz'] = array();
            }
            $resDev = $modLineDev->where($map)->order('cid')->select();
            if($resDev){
                $row['devs'] = $resDev;
            }else{
                $row['devs'] = array();
            }
        }
        $this->ajaxRetArray($resLines);
    }
    public function pointset(){
        $lineid = $_REQUEST['lineid'];
        $modLine = M('Lines');
        $modLineDev = M('LinesDev');
        $modXyz = M('LinesXyz');
        $resLine = $modLine->where("lineid=$lineid")->find();
        if($resLine){
            $metadata['hasline'] = true;
            $metadata['lineid'] = $resLine['lineid'];
            $metadata['linename'] = $resLine['linename'];
            $metadata['linetype'] = $resLine['linetype'];
            $resDev = $modLineDev->where("lineid=$lineid")->order('cid')->select();
            if($resDev){
                $metadata['devs'] = $resDev;
            }else{
                $metadata['devs'] = array();
            }
            $resXyz = $modXyz->where('lineid='.$resLine['lineid'])->select();
            if($resXyz){
                $ret = $resXyz;
            }else{
                $ret = array();
            }
            $this->ajaxReturnWithMeta($ret,count($ret),true,$metadata);
        }else{
            $metadata['hasline'] = false;
            $this->ajaxReturnWithMeta(null,'没有连接线!',true,$metadata);
        }
    }
    public function addPoint(){
        $lineid = $_REQUEST['lineid'];
        $xyz = $_REQUEST['xyz'];
        $modXyz = M('LinesXyz');
        $data['lineid'] = $lineid;
        $data['xyz'] = $xyz;
        $modXyz->add($data);
        $ret = array('lineid'=>$lineid);
        $this->ajaxReturn($ret,'',true);
    }
    
    public function delPoint(){
        $lineid = $_REQUEST['lineid'];
        $lid = $_REQUEST['lid'];
        $modXyz = M('LinesXyz');
        $data['lineid'] = $lineid;
        $data['lid'] = $lid;
        $modXyz->where($data)->delete();
        $ret = array('lineid'=>$lineid);
        $this->ajaxReturn($ret,'',true);
    }
    
    public function savePoint(){
        $lineid = $_REQUEST['lineid'];
        $xyz = $_REQUEST['xyz'];
        $lid = $_REQUEST['lid'];
        $modXyz = M('LinesXyz');
        $data['xyz'] = $xyz;
        $where['lid'] = $lid;
        $modXyz->where($where)->save($data);
        $ret = array('lineid'=>$lineid);
        $this->ajaxReturn($ret,'',true);
    }
}